package com.authine.cloudpivot.ext.applicationservice.v1.sourcing;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.CheckPriceService;
import com.authine.cloudpivot.ext.applicationservice.InquiryService;
import com.authine.cloudpivot.ext.applicationservice.QuotationService;
import com.authine.cloudpivot.ext.applicationservice.v1.sourcing.vo.*;
import com.authine.cloudpivot.ext.constants.ApiClientConstants;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.GatewayParam;
import com.authine.cloudpivot.ext.dto.GatewayResponse;
import com.authine.cloudpivot.ext.dto.inquiry.InquiryGoodsClarifyDto;
import com.authine.cloudpivot.ext.dto.inquiry.InquiryGoodsDto;
import com.authine.cloudpivot.ext.dto.quotation.QuotationGoodsApprovedHistoryDto;
import com.authine.cloudpivot.ext.dto.quotation.QuotationGoodsDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.enums.inquiry.InquiryStatusEnum;
import com.authine.cloudpivot.ext.enums.inquiry.QuotationStatusEnum;
import com.authine.cloudpivot.ext.enums.inquiry.VendorScopeEnum;
import com.authine.cloudpivot.ext.enums.system.ArchitectureCateEnum;
import com.authine.cloudpivot.ext.enums.system.OrganizationAttributeEnum;
import com.authine.cloudpivot.ext.exception.InquiryException;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.cloudpivot.ext.utils.system.*;
import com.authine.common.util.DateUtils;
import com.authine.common.util.ObjectMapperUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.AttachmentFormat;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.Operator;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import com.authine.mvp.app.org.dto.domainvo.DeptOrUserVO;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.cloudpivot.ext.utils.JdbcTemplateUtils.getTableName;
import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName SourcingInquiry
 * @Description: 寻源中心-询价接口
 * @Author fj
 * @Date 2021/5/14
 * @Version V1.0
 **/
@Path("SourcingInquiry")
@Slf4j
public class SourcingInquiry extends ApplicationService {
    private final InquiryService inquiryService = new InquiryService();
    private final CheckPriceService checkPriceService = new CheckPriceService();
    private final QuotationService quotationService = new QuotationService();
    private static final String inquiryName = getTableName(ModelConst.T_INQUIRY);
    private static final String inquiryGoodsName = getTableName(ModelConst.T_INQUIRY_GOODS);
    private static final String quotationGoodsName = getTableName(ModelConst.T_QUOTATION_GOODS);
    private static final String quotationGoodsAppHisName = getTableName(ModelConst.T_QUOTATION_GOODS_APP_HIS);
    private static final String GoodsPurchaseName = JdbcTemplateUtils.getTableName(ModelConst.T_GOODS_PURCHASE, AppConst.COMMODITYMATERIALS);
    private static final String DemandGoodsName = JdbcTemplateUtils.getTableName(ModelConst.T_DEMAND_GOODS, AppConst.DEMAND_POOL);
    private static final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 查询澄清记录
     *
     * @param gatewayParam 请求参数
     * @return 响应结果
     */
    @Path("recordList")
    @POST
    @Operation(summary = "查询澄清记录", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<InquiryGoodsClarifyVO>> recordList(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", Lists.newArrayList());
        }
        if (!gatewayParam.getQuery().containsKey("inquiryGoodsId")) {
            return GatewayResponse.failed(0, "参数错误", Lists.newArrayList());
        }

        // 通过询价商品id获取澄清记录
        SingleResponse<BOList> clarifyResult = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS_CLARIFY, "inquiry_goods_id", gatewayParam.getQuery().get("inquiryGoodsId"));
        log.info("----------------------clarifyResult：{}------------------------", JSONObject.toJSONString(clarifyResult));
        List<InquiryGoodsClarifyVO> inquiryGoodsClarifyVOList;
        if (clarifyResult.isSuccess()) {
            if (clarifyResult.getData().getTotal() > 0) {
                JSONArray array = JSONUtil.parseArray(clarifyResult.getData().getData());
                inquiryGoodsClarifyVOList = JSONUtil.toList(array, InquiryGoodsClarifyVO.class);
            } else {
                return GatewayResponse.failed(0, "暂无澄清记录", Lists.newArrayList());
            }
        } else {
            return GatewayResponse.success(0, "查询失败，请稍后重试", Lists.newArrayList());
        }
        return GatewayResponse.success(inquiryGoodsClarifyVOList.size(), "查询成功", inquiryGoodsClarifyVOList);
    }

    /**
     * 供应商创建澄清记录
     *
     * @param gatewayParam 请求参数
     * @return 响应结果
     */
    @Path("recordSave")
    @POST
    @Operation(summary = "供应商创建澄清记录", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> recordSave(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        Map<String, Object> body = gatewayParam.getBody();
        if (!body.containsKey("inquiryGoodsId")) {
            return GatewayResponse.failed(0, "询价商品id不能为空", null);
        }
        if (!body.containsKey("clarifyTips")) {
            return GatewayResponse.failed(0, "澄清内容不能为空", null);
        }
        if (!body.containsKey("attachment")) {
            return GatewayResponse.failed(0, "附件不能为空", null);
        }

        // 通过询价商品id获取询价商品信息
        SingleResponse<BOList> inquiryGoods = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", body.get("inquiryGoodsId"));
        log.info("----------------------inquiryGoods：{}------------------------", JSONObject.toJSONString(inquiryGoods));
        if (inquiryGoods.getData().getTotal() == 0) {
            return GatewayResponse.failed(0, "询价商品" + body.get("inquiryGoodsId") + "不存在！", null);
        }

        // 获取澄清状态
        String clarifyStatus = String.valueOf(inquiryGoods.getData().getData().get(0).get("clarify_status"));

        // 设置澄清内容
        Map<String, Object> clarifyMap = Maps.newHashMap();
        InquiryGoodsClarifyDto inquiryGoodsClarify = new InquiryGoodsClarifyDto();
        inquiryGoodsClarify.setInquiryGoodsId(String.valueOf(body.get("inquiryGoodsId")));
        inquiryGoodsClarify.setClarifyTips(String.valueOf(body.get("clarifyTips")));
        inquiryGoodsClarify.setAttachment(ObjectMapperUtils.readValue(ObjectMapperUtils.toJSONString(body.get("attachment")), AttachmentFormat.class));
        clarifyStatus = inquiryService.buildClarifyMap(clarifyMap, inquiryGoodsClarify, clarifyStatus);

        // 新增澄清记录
        SingleResponse<BO> createClarifyResult = BoServiceUtils.createBo(ModelConst.T_INQUIRY_GOODS_CLARIFY, Collections.singletonList(clarifyMap));
        log.info("----------------------create clarify result：{}------------------------", JSONObject.toJSONString(createClarifyResult));

        // 更新询价商品澄清状态
        inquiryService.clarify(inquiryGoods.getData().getData().get(0), clarifyStatus);
        return GatewayResponse.success(0, "澄清成功", body.get("inquiryGoodsId").toString());
    }

    /**
     * 分页查询询价商品
     *
     * @param gatewayParam
     * @return
     */
    @Path("inquiryGoodsPage")
    @POST
    @Operation(summary = "分页查询询价商品", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<InquiryGoodsVO>> inquiryGoodsPage(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", null);
        }
        Map<String, Object> query = gatewayParam.getQuery();
        List<String> columnNames = Lists.newArrayList();
        List<Operator> operators = Lists.newArrayList();
        List<Object> columnValues = Lists.newArrayList();
        if (query.containsKey("newIds") && query.get("newIds") != null) {
            columnNames.add("id");
            operators.add(Operator.IN);
            String newIds = MapUtils.getString(query, "newIds");
            List<String> id = Arrays.asList(newIds.split(","));
            columnValues.add(id);
        }
        if (query.containsKey("address") && query.get("address") != null) {
            columnNames.add("address");
            operators.add(Operator.EQ);
            columnValues.add(query.get("address"));
        }
        if (query.containsKey("brand") && query.get("brand") != null) {
            columnNames.add("brand");
            operators.add(Operator.EQ);
            columnValues.add(query.get("brand"));
        }
        if (query.containsKey("spec") && query.get("spec") != null) {
            columnNames.add("spec");
            operators.add(Operator.EQ);
            columnValues.add(query.get("spec"));
        }
        if (query.containsKey("model") && query.get("model") != null) {
            columnNames.add("model");
            operators.add(Operator.EQ);
            columnValues.add(query.get("model"));
        }

        String page = (String) query.get("page");
        Integer pageIndex = 0;
        if (query.get("page") != null) {
            pageIndex = Integer.valueOf(page);
        }
        String limit = (String) query.get("limit");
        Integer pageSize = 20;
        if (query.get("limit") != null) {
            pageSize = Integer.valueOf(limit);
        }

        String[] strings = new String[columnNames.size()];
        Operator[] operators1 = new Operator[operators.size()];
        // 查询列表
        SingleResponse<BOList> boListSingleResponse = BoServiceUtils.findListAndLimit(ModelConst.T_INQUIRY_GOODS, columnNames.toArray(strings), columnValues.toArray(), operators.toArray(operators1), pageIndex, pageSize);

        log.info("----------------------boListSingleResponse：{}------------------------", JSONObject.toJSONString(boListSingleResponse));
        List<InquiryGoodsVO> inquiryGoodsVOList;
        if (boListSingleResponse.isSuccess()) {
            if (boListSingleResponse.getData().getTotal() > 0) {
                JSONArray array = JSONUtil.parseArray(boListSingleResponse.getData().getData());
                inquiryGoodsVOList = JSONUtil.toList(array, InquiryGoodsVO.class);
            } else {
                return GatewayResponse.failed(0, "无记录", Lists.newArrayList());
            }
        } else {
            return GatewayResponse.success(0, "查询失败，请稍后重试", Lists.newArrayList());
        }
        return GatewayResponse.success(inquiryGoodsVOList.size(), "查询成功", inquiryGoodsVOList);
    }

    /**
     * 分页查询询价
     *
     * @param gatewayParam
     * @return
     */
    @Path("inquiryPage")
    @POST
    @Operation(summary = "分页查询询价", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<InquiryVO>> inquiryPage(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", Lists.newArrayList());
        }
        Map<String, Object> query = gatewayParam.getQuery();
        List<String> columnNames = Lists.newArrayList();
        List<Operator> operators = Lists.newArrayList();
        List<Object> columnValues = Lists.newArrayList();
        if (query.containsKey("id") && query.get("id") != null) {
            columnNames.add("id");
            operators.add(Operator.EQ);
            columnValues.add(query.get("id"));
        }
        if (query.containsKey("inquiryGoodsIds") && query.get("inquiryGoodsIds") != null) {
            String inquiryGoodsIds = MapUtils.getString(query, "inquiryGoodsIds");
            List<String> ids = Arrays.asList(inquiryGoodsIds.split(","));
            SingleResponse<BOList> listByIn = BoServiceUtils.findListByIn(ModelConst.T_INQUIRY_GOODS, "id", ids);
            List<Map<String, Object>> data = listByIn.getData().getData();
            Object inquiryId = data.get(0).get("inquiry_id");
            columnNames.add("id");
            operators.add(Operator.IN);
            columnValues.add(inquiryId);
        }
        if (query.containsKey("contacts") && query.get("contacts") != null) {
            columnNames.add("contacts");
            operators.add(Operator.EQ);
            columnValues.add(query.get("contacts"));
        }
        if (query.containsKey("mobile") && query.get("mobile") != null) {
            columnNames.add("mobile");
            operators.add(Operator.EQ);
            columnValues.add(query.get("mobile"));
        }
        if (query.containsKey("name") && query.get("name") != null) {
            columnNames.add("name");
            operators.add(Operator.EQ);
            columnValues.add(query.get("name"));
        }

        String page = (String) query.get("page");
        Integer pageIndex = 0;
        if (query.get("page") != null) {
            pageIndex = Integer.valueOf(page);
        }
        String limit = (String) query.get("limit");
        Integer pageSize = 20;
        if (query.get("limit") != null) {
            pageSize = Integer.valueOf(limit);
        }

        String[] strings = new String[columnNames.size()];
        Operator[] operators1 = new Operator[operators.size()];
        // 分页查询询价列表
        SingleResponse<BOList> listByOrAndLimit = BoServiceUtils.findListAndLimit(ModelConst.T_INQUIRY, columnNames.toArray(strings), columnValues.toArray(), operators.toArray(operators1), pageIndex, pageSize);
        log.info("----------------------listByOrAndLimit：{}------------------------", JSONObject.toJSONString(listByOrAndLimit));

        List<InquiryVO> inquiryVOS = JSONUtil.toList(JSONUtil.parseArray(listByOrAndLimit.getData().getData()), InquiryVO.class);

        listByOrAndLimit.getData().getData().forEach(inquiryMap -> {
            List<InquiryGoodsVO> inquiryGoodsVOS = JSONUtil.toList(JSONUtil.parseArray(inquiryMap.get("c5uxuiw5i4qo")), InquiryGoodsVO.class);
            inquiryVOS.forEach(inquiryVO -> {
                if (inquiryVO.getId().equals(inquiryMap.get("id"))) {
                    inquiryVO.setInquiryGoods(inquiryGoodsVOS);
                }
            });
        });
        return GatewayResponse.success(inquiryVOS.size(), "查询成功", inquiryVOS);
    }

    /**
     * 查询邀请供应商列表
     *
     * @param gatewayParam
     * @return
     */
    @Path("inviteVenodrList")
    @POST
    @Operation(summary = "查询邀请供应商列表", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<InviteVenodrVO>> inviteVenodrList(@Parameter GatewayParam gatewayParam) {

        //获取当前登录人
        UserDto currentUser = UserUtils.getCurrentUser();

        List<SelectorFormat> organization_id = currentUser.getOrganization_id();
        String customerId = organization_id.get(0).getId();

        //客户查询被邀请的供应商组织
        List<String> listVendorByCustomerId = OrgUtils.listVendorByCustomerId(customerId);

        //邀请供应商列表
        List<Map<String, Object>> maps = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                .selectField("id,createdBy,createdDept,createdTime,`owner`,ownerDept,modifiedBy,modifiedTime,`status`,JSON_UNQUOTE( parent_id -> '$.id' ) AS parent_id,account_id,JSON_UNQUOTE( business_member_id -> '$.id' ) AS business_member_id,JSON_UNQUOTE( transaction_organization_id -> '$.id' ) AS transaction_organization_id,extends_attr,extends_attr,`name`,parent_name,business_member_name,description,role_names,organization_product_line,business_scope,license_code,credit_identifier,legal_representative,registered_capital,memo,purchase_quota,attachment,platform,`virtual`,statement_cycle,c79vqtc1vcvk,reconciliation_day_strategy,payment_day_strategy,small_scale,small_scale_rate,freight_ratio,pay_appoint_way,sales_area,major_brand,quotation_decimal_limit,`level`,enabled,del,version,connect,cellphone,email,qq,JSON_UNQUOTE( platform_id -> '$.id' ) AS platform_id,platform_name,invite_user,goods_automatic_matching,deleted,preNodeId,nextNodeId,muti_org_id,org_attributeValue,org_attributeName")
                .eq("id", listVendorByCustomerId.get(1))
                .queryForList();
        log.info("----------------------maps：{}------------------------", JSONObject.toJSONString(maps));

        List<InviteVenodrVO> inviteVenodrVOS = JSONUtil.toList(JSONUtil.parseArray(maps), InviteVenodrVO.class);
        return GatewayResponse.success(inviteVenodrVOS.size(), "查询成功", inviteVenodrVOS);
    }

    /**
     * 供应商分页查询还价
     *
     * @param gatewayParam
     * @return
     */
    @Path("/quotationApproveBack")
    @POST
    @Operation(summary = "供应商分页查询还价", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<Map>> quotationApproveBack(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", Lists.newArrayList());
        }
        Map<String, Object> query = gatewayParam.getQuery();

        String page = (String) query.get("page");
        Integer pageIndex = 0;
        if (query.get("page") != null) {
            pageIndex = Integer.valueOf(page);
        }
        String limit = (String) query.get("limit");
        Integer pageSize = 20;
        if (query.get("limit") != null) {
            pageSize = Integer.valueOf(limit);
        }

        //获取当前登录人
        UserDto currentUser = UserUtils.getCurrentUser();//暂时写死

        //通过当前登录人查询报价商品
        SingleResponse<BOList> listBySimple = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS, "member_id", "2c9ac00d78a69a5a0178abed5717000a");
        List<Object> list = listBySimple.getData().getData().stream().map(map -> {
            Object id = map.get("id");
            log.info("----------------------id：{}------------------------", JSONObject.toJSONString(id));
            return id;
        }).collect(Collectors.toList());

        String str = "quotation_id";
        String[] split = str.split(",");
        for (String string : split) {
            System.out.println(string);
        }

        Object[] objList = new Object[]{list};
        Operator[] operatorss = new Operator[]{Operator.IN};

        //通过报价分页查询供应商还价
        SingleResponse<BOList> listByOrAndLimit = BoServiceUtils.findListAndLimit(ModelConst.T_QUOTATION_GOODS_APP_HIS, split, objList, operatorss, pageIndex, pageSize);
        log.info("----------------------listByOrAndLimit：{}------------------------", JSONObject.toJSONString(listByOrAndLimit));
        List<Map> approveList = new LinkedList<>();
        for (Map<String, Object> map : listByOrAndLimit.getData().getData()) {
            Map<String, Object> a = new LinkedHashMap<>();
            a.put("id", map.get("id"));
            SingleResponse<BOList> bySimple = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS, "id", map.get("quotation_id"));
            a.put("quotationId", bySimple.getData().getData().get(0).get("id"));
            a.put("approvedFailedReason", map.get("approved_failed_reason"));
            a.put("name", map.get("name"));
            a.put("brand", map.get("brand"));
            a.put("model", map.get("model"));
            a.put("spec", map.get("spec"));
            a.put("sku", map.get("sku"));
            a.put("num", map.get("num"));
            a.put("unit", map.get("unit"));
            a.put("packageNum", map.get("package_num"));
            a.put("packageUnit", map.get("package_unit"));
            a.put("price", map.get("price"));
            a.put("pretaxPrice", map.get("pretax_price"));
            a.put("freight", map.get("freight"));
            a.put("pretaxFreight", map.get("pretax_freight"));
            a.put("taxRateFreight", map.get("tax_rate_freight"));
            a.put("delivery", map.get("delivery"));
            a.put("total", map.get("total"));
            a.put("pretaxTotal", map.get("pretax_total"));
            a.put("amount", map.get("amount"));
            a.put("pretaxAmount", map.get("pretax_amount"));
            a.put("taxPayable", map.get("tax_payable"));
            a.put("taxRate", map.get("tax_rate"));
            a.put("address", map.get("address"));
            a.put("time", map.get("createdTime"));
            a.put("counterPrePrice", map.get("counter_pre_price"));
            a.put("vendorName", bySimple.getData().getData().get(0).get("member_full_name"));
            a.put("vendorMobile", bySimple.getData().getData().get(0).get("member_mobile"));
            a.put("vendorEmail", bySimple.getData().getData().get(0).get("member_email"));
            a.put("expire", bySimple.getData().getData().get(0).get("expire"));
            a.put("last", bySimple.getData().getData().get(0).get("modifiedTime"));
            a.put("description", bySimple.getData().getData().get(0).get("description"));
            a.put("attachment", bySimple.getData().getData().get(0).get("attachment"));
            a.put("quotationType", bySimple.getData().getData().get(0).get("auto_quotation"));
            a.put("quotationStatus", bySimple.getData().getData().get(0).get("status"));
            a.put("remarkMessage", bySimple.getData().getData().get(0).get("remark_message"));
            a.put("inquiryExpire", bySimple.getData().getData().get(0).get("inquiry_expire_time"));
            approveList.add(a);
        }
        return GatewayResponse.success(approveList.size(), "查询成功", approveList);
    }

    /**
     * 还价历史查询
     *
     * @param gatewayParam
     * @return
     */
    @Path("/quotationHistoryList")
    @POST
    @Operation(summary = "还价历史查询", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<QuotationGoodsAppHisVO>> quotationHistoryList(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", Lists.newArrayList());
        }
        Map<String, Object> query = gatewayParam.getQuery();
        if (!query.containsKey("quotationGoodsId")) {
            return GatewayResponse.failed(0, "报价商品id不能为空", null);
        }

        BOList boList = new BOList();
        // 获取表名
        Map<String, Object> parameter = Maps.newHashMap();
        // 拼接sql
        StringBuilder totalSql = new StringBuilder();// 获取总数
        StringBuilder querySql = new StringBuilder();// 查询条件
        StringBuilder listSql = new StringBuilder();// 获取结果

        totalSql.append("select count(*) as count from (\n");
        totalSql.append("select h.* from \n");
        querySql.append(quotationGoodsAppHisName).append(" as h\n");
        querySql.append("left join\n");
        querySql.append(quotationGoodsName).append(" as qg\n");
        querySql.append("on h.quotation_id = qg.id\n");
        querySql.append("left join\n");
        querySql.append(inquiryGoodsName).append(" as ig\n");
        querySql.append("on ig.id = qg.inquiry_goods_id\n");
        querySql.append("left join\n");
        querySql.append(inquiryName).append(" as i\n");
        querySql.append("on i.id = ig.inquiry_id\n");
        querySql.append("where i.member_id -> '$.id' = :member_id\n");
        parameter.put("member_id", "2c9ac00d78a69a5a0178abed5717000a");
        if (query.containsKey("quotationGoodsId") && query.get("quotationGoodsId") != null) {
            String str = String.valueOf(query.get("quotationGoodsId"));
            String[] ids = str.split(",");
            querySql.append("and qg.id in (:ids)\n");
            parameter.put("ids", Arrays.asList(ids));
        }
        listSql.append("select h.* from \n");
        listSql.append(querySql);
        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSql.toString()));

        List<Map<String, Object>> result = jdbcTemplate.queryForList(listSql.toString(), parameter);
        log.info("-------------------还价历史查询数据：{}-------------------", JSONObject.toJSONString(result));

        // 对结果进行格式化
        BoResultFormat.resultFormat(result, ModelConst.T_QUOTATION_GOODS_APP_HIS, true);
        boList.setData(result);
        boList.setSchemaCode(ModelConst.T_QUOTATION_GOODS_APP_HIS);
        log.info("-------------------boList：{}-------------------", JSONObject.toJSONString(boList));
        List<QuotationGoodsAppHisVO> quotationGoodsAppHisVOList = JSONUtil.toList(JSONUtil.parseArray(boList.getData()), QuotationGoodsAppHisVO.class);

        return GatewayResponse.success(quotationGoodsAppHisVOList.size(), "查询成功", quotationGoodsAppHisVOList);
    }

    /**
     * 分页查询报价
     *
     * @param gatewayParam
     * @return
     */
    @Path("/quotationPage")
    @POST
    @Operation(summary = "分页查询报价", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<Map>> quotationPage(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数为空", Lists.newArrayList());
        }
        Map<String, Object> query = gatewayParam.getQuery();
        List<String> columnNames = Lists.newArrayList();
        List<Operator> operators = Lists.newArrayList();
        List<Object> columnValues = Lists.newArrayList();

        if (query.containsKey("address") && query.get("address") != null) {
            columnNames.add("address");
            operators.add(Operator.EQ);
            columnValues.add(query.get("address"));
        }
        if (query.containsKey("brand") && query.get("brand") != null) {
            columnNames.add("brand");
            operators.add(Operator.EQ);
            columnValues.add(query.get("brand"));
        }
        if (query.containsKey("customerOrgName") && query.get("customerOrgName") != null) {
            columnNames.add("organization_company_name");
            operators.add(Operator.EQ);
            columnValues.add(query.get("customerOrgName"));
        }
        if (query.containsKey("model") && query.get("model") != null) {
            columnNames.add("model");
            operators.add(Operator.EQ);
            columnValues.add(query.get("model"));
        }
        if (query.containsKey("name") && query.get("name") != null) {
            columnNames.add("name");
            operators.add(Operator.EQ);
            columnValues.add(query.get("name"));
        }
        if (query.containsKey("newInquiryGoodsIds") && query.get("newInquiryGoodsIds") != null) {
            columnNames.add("inquiry_goods_id");
            operators.add(Operator.IN);
            String newInquiryGoodsIds = MapUtils.getString(query, "newInquiryGoodsIds");
            List<String> id = Arrays.asList(newInquiryGoodsIds.split(","));
            columnValues.add(id);
        }
        if (query.containsKey("newQuotationGoodsIds") && query.get("newQuotationGoodsIds") != null) {
            columnNames.add("id");
            operators.add(Operator.IN);
            String newQuotationGoodsIds = MapUtils.getString(query, "newQuotationGoodsIds");
            List<String> id = Arrays.asList(newQuotationGoodsIds.split(","));
            columnValues.add(id);
        }
        if (query.containsKey("newStatus") && query.get("newStatus") != null) {
            columnNames.add("quotation_goods_status");
            operators.add(Operator.IN);
            String newStatus = MapUtils.getString(query, "newStatus");
            List<String> status = Arrays.asList(newStatus.split(","));
            columnValues.add(status);
        }

        String page = (String) query.get("page");
        Integer pageIndex = 0;
        if (query.get("page") != null) {
            pageIndex = Integer.valueOf(page);
        }
        String limit = (String) query.get("limit");
        Integer pageSize = 20;
        if (query.get("limit") != null) {
            pageSize = Integer.valueOf(limit);
        }

        String[] strings = new String[columnNames.size()];
        Operator[] operatorss = new Operator[operators.size()];


        //获取当前登录用户
        UserDto currentUser = UserUtils.getCurrentUser();
        columnNames.add("member_id");
        operators.add(Operator.EQ);
        columnValues.add("2c9ac00d78a69a5a0178abed5717000a");

        //通过当前登录用户会员id分页查询报价商品列表
        SingleResponse<BOList> listByOrAndLimit = BoServiceUtils.findListAndLimit(ModelConst.T_QUOTATION_GOODS, columnNames.toArray(strings), columnValues.toArray(), operators.toArray(operatorss), pageIndex, pageSize);
        log.info("----------------------listByOrAndLimit：{}------------------------", JSONObject.toJSONString(listByOrAndLimit));
        List<Map> approveList = new LinkedList<>();
        for (Map<String, Object> map : listByOrAndLimit.getData().getData()) {
            Map<String, Object> a = new LinkedHashMap<>();
            a.put("quotationGoodsId", map.get("id"));
            //通过报价商品查询询价商品
            SingleResponse<BOList> listBySimple = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", map.get("inquiry_goods_id"));
            log.info("----------------------listBySimple：{}------------------------", JSONObject.toJSONString(listBySimple));
            List<Map> approveListTwo = new LinkedList<>();
            for (Map<String, Object> maptwo : listBySimple.getData().getData()) {
                Map<String, Object> b = new LinkedHashMap<>();
                b.put("id", maptwo.get("id"));
                b.put("del", maptwo.get("deleted"));
                b.put("last", maptwo.get("modifiedTime"));
                b.put("time", maptwo.get("createdTime"));
                if (maptwo.get("modifiedBy") != null) {
                    b.put("modifiedBy", ((DeptOrUserVO) map.get("modifiedBy")).getName());
                }
                if (maptwo.get("modifiedBy") != null) {
                    b.put("modifiedBy", ((DeptOrUserVO) map.get("modifiedBy")).getName());
                }
                //通过询价商品查询询价单
                SingleResponse<BOList> bySimple = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", maptwo.get("inquiry_id"));
                log.info("----------------------bySimple：{}------------------------", JSONObject.toJSONString(bySimple));
                List<Map> approveListThree = new LinkedList<>();
                for (Map<String, Object> mapthree : bySimple.getData().getData()) {
                    Map<String, Object> c = new LinkedHashMap<>();
                    c.put("id", mapthree.get("id"));
                    c.put("del", mapthree.get("deleted"));
                    c.put("last", mapthree.get("modifiedTime"));
                    c.put("time", mapthree.get("createdTime"));
                    if (maptwo.get("modifiedBy") != null) {
                        c.put("modifiedBy", ((DeptOrUserVO) map.get("modifiedBy")).getName());
                    }
                    if (maptwo.get("modifiedBy") != null) {
                        c.put("modifiedBy", ((DeptOrUserVO) map.get("modifiedBy")).getName());
                    }
                    if (maptwo.get("member_id") != null) {
                        c.put("memberId", ((List<SelectorFormat>) map.get("member_id")).get(0).getId());
                    }
                    c.put("memberName", mapthree.get("member_name"));
                    c.put("accountPeriod", mapthree.get("account_period"));
                    if (maptwo.get("target_department_id") != null) {
                        c.put("targetDepartmentId", ((List<SelectorFormat>) map.get("target_department_id")).get(0).getId());
                    }
                    c.put("targetDepartmentName", mapthree.get("target_department_name"));
                    if (maptwo.get("department_id") != null) {
                        c.put("departmentId", ((List<SelectorFormat>) map.get("department_id")).get(0).getId());
                    }
                    c.put("departmentName", mapthree.get("department_name"));
                    c.put("name", mapthree.get("name"));
                    c.put("expire", mapthree.get("expire"));
                    c.put("vendorScope", mapthree.get("vendor_scope"));
                    c.put("contacts", mapthree.get("contacts"));
                    c.put("mobile", mapthree.get("mobile"));
                    c.put("qq", mapthree.get("qq"));
                    c.put("quoteTotalStrategy", mapthree.get("quote_total_strategy"));
                    c.put("quoteHermeticStrategy", mapthree.get("quote_hermetic_strategy"));
                    c.put("quoteFreightLimit", mapthree.get("quote_freight_limit"));
                    c.put("quoteTaxRateLimit", mapthree.get("quote_tax_rate_limit"));
                    c.put("quoteMultiplePurchases", mapthree.get("quote_multiple_purchases"));
                    c.put("quoteMinTimeStrategy", mapthree.get("quote_min_time_strategy"));
                    c.put("quotePublicBidding", mapthree.get("quote_public_bidding"));
                    c.put("memos", mapthree.get("memos"));
                    c.put("description", mapthree.get("description"));
                    c.put("clientInquiryId", mapthree.get("client_inquiry_id"));
                    c.put("costCenterName", mapthree.get("cost_center_name"));
                    c.put("extendsAttr", mapthree.get("extendAttr"));
                    c.put("inquiryVendorSMSSize", mapthree.get("inquiryVendorSMSSize"));
                    c.put("parentId", mapthree.get("parentId"));
                    if (maptwo.get("vendor_department_id") != null) {
                        c.put("vendorOrgId", ((List<SelectorFormat>) map.get("vendor_department_id")).get(0).getId());
                    }
                    c.put("memMobile", map.get("member_mobile"));
                    c.put("userName", currentUser.getUsername());
                    c.put("status", mapthree.get("status"));
                    c.put("inquiryDepartmentName", mapthree.get("inquiryDepartmentName"));
                    if (maptwo.get("organization_id") != null) {
                        c.put("organizationId", ((List<SelectorFormat>) map.get("organization_id")).get(0).getId());
                    }
                    c.put("organizationCompanyName", mapthree.get("organization_company_name"));
                    c.put("partakeCount", maptwo.get("partake_count"));
                    c.put("quoteCount", maptwo.get("quote_partake_count"));
                    c.put("remainderDay", mapthree.get("remainderDay"));
                    c.put("clientId", mapthree.get("client_id"));
                    c.put("clientUserId", mapthree.get("client_user_id"));
                    c.put("wholeNotInvolved", mapthree.get("wholeNotInvolved"));
                    c.put("organizationVendorId", mapthree.get("organizationVendorId"));
                    c.put("vmiInquiry", mapthree.get("vmi_inquiry"));
                    c.put("expireStart", mapthree.get("expireStart"));
                    c.put("expireEnd", mapthree.get("expireEnd"));
                    c.put("submit", mapthree.get("submit"));
                    c.put("logisticsDemand", mapthree.get("logistics_demand"));
                    c.put("releaseTime", mapthree.get("release_time"));
                    c.put("notequalsOrganizationCompanyName", mapthree.get("notequalsOrganizationCompanyName"));
                    c.put("equalsOrganizationCompanyName", mapthree.get("equalsOrganizationCompanyName"));
                    approveListThree.add(c);
                }
                b.put("inquiry", approveListThree);
                b.put("demandGoodsId", maptwo.get("demand_goods_id"));
                b.put("pass", maptwo.get("pass"));
                b.put("reason", maptwo.get("reason"));
                b.put("clientId", maptwo.get("client_id"));
                b.put("clientInquiryGoodsId", maptwo.get("client_inquiry_goods_id"));
                b.put("status", maptwo.get("inquiry_goods_status"));
                b.put("platformCategoryName", maptwo.get("platform_category_name"));
                b.put("orgCategoryName", maptwo.get("org_category_name"));
                b.put("sku", maptwo.get("sku"));
                b.put("barCode", maptwo.get("bar_code"));
                b.put("name", maptwo.get("name"));
                b.put("brand", maptwo.get("brand"));
                b.put("model", maptwo.get("model"));
                b.put("spec", maptwo.get("spec"));
                b.put("address", maptwo.get("address"));
                b.put("delivery", maptwo.get("delivery"));
                b.put("num", maptwo.get("num"));
                b.put("unit", maptwo.get("unit"));
                b.put("packageNum", maptwo.get("package_num"));
                b.put("packageUnit", maptwo.get("package_unit"));
                b.put("quoteCount", maptwo.get("quote_count"));
                b.put("partakeCount", maptwo.get("partake_count"));
                b.put("itemType", maptwo.get("item_type"));
                b.put("quoteMaxPriceLimit", maptwo.get("quote_max_price_limit"));
                b.put("quoteEditLimit", maptwo.get("quote_edit_limit"));
                if (maptwo.get("attachment") != null) {
                    b.put("attachment", ((ArrayList<AttachmentFormat>) maptwo.get("attachment")).get(0).getName());
                }
                b.put("originalInquiryGoodsId", maptwo.get("original_inquiry_goods_id"));
                b.put("url", maptwo.get("url"));
                b.put("memo", maptwo.get("memo"));
                b.put("description", maptwo.get("description"));
                b.put("safetyStockNum", maptwo.get("safetyStockNum"));
                b.put("maximumStock", maptwo.get("maximum_stock"));
                b.put("picketaged", maptwo.get("picketaged"));
                b.put("clarifyRecord", maptwo.get("clarify_record"));
                if (maptwo.get("demand_department") != null) {
                    b.put("demandDepartment", ((List<SelectorFormat>) maptwo.get("demand_department")).get(0).getName());
                }
                b.put("closingReason", maptwo.get("closing_reason"));
                b.put("isRequireSample", maptwo.get("is_require_sample"));
                b.put("participation", maptwo.get("participation"));
                b.put("clarifyStatus", maptwo.get("clarify_status"));
                b.put("clarifyNumber", maptwo.get("clarify_number"));
                b.put("area", maptwo.get("area"));
                b.put("company", maptwo.get("company"));
                b.put("warehouse", maptwo.get("warehouse"));
                b.put("clientPurchaseRequest", maptwo.get("client_purchase_request"));
                b.put("quotationVendorIds", maptwo.get("quotation_vendor_ids"));
                b.put("extendsAttr", maptwo.get("extendsAttr"));
                b.put("attachments", maptwo.get("attachment"));
                b.put("demandMemberName", maptwo.get("demandMemberName"));
                b.put("demandDepartmentName", maptwo.get("demandDepartmentName"));
                b.put("ifPricing", maptwo.get("ifPricing"));
                b.put("closeType", maptwo.get("closeType"));
                b.put("quotationGoodsEntity", maptwo.get("quotationGoodsEntity"));
                b.put("quotationSupplierName", maptwo.get("quotationSupplierName"));
                b.put("memberFullName", map.get("member_full_name"));
                b.put("isMatching", maptwo.get("isMatching"));
                b.put("quotaCountScope", maptwo.get("quotaCountScope"));
                b.put("querySource", maptwo.get("querySource"));
                approveListTwo.add(b);
            }
            a.put("inquiryGoodsId", listBySimple.getData().getData().get(0).get("id"));
            a.put("status", map.get("quotation_goods_status"));
            a.put("name", map.get("name"));
            a.put("brand", map.get("brand"));
            a.put("model", map.get("model"));
            a.put("spec", map.get("spec"));
            a.put("num", map.get("num"));
            a.put("unit", map.get("unit"));
            a.put("packageNum", map.get("package_num"));
            a.put("packageUnit", map.get("package_unit"));
            a.put("price", map.get("price"));
            a.put("total", map.get("total"));
            a.put("freight", map.get("freight"));
            a.put("amount", map.get("amount"));
            a.put("expire", map.get("expire"));
            a.put("delivery", map.get("delivery"));
            a.put("address", map.get("address"));
            a.put("pretaxPrice", map.get("pretax_price"));
            a.put("pretaxFreight", map.get("pretax_freight"));
            a.put("pretaxAmount", map.get("pretax_amount"));
            a.put("taxRate", map.get("tax_rate"));
            a.put("taxPayable", map.get("tax_payable"));
            a.put("taxRateFreight", map.get("tax_rate_freight"));
            a.put("description", map.get("description"));
            a.put("sku", map.get("sku"));
            if (map.get("member_id") != null) {
                a.put("vendorId", ((List<SelectorFormat>) map.get("member_id")).get(0).getId());
            }
            a.put("vendorName", map.get("member_name"));
            a.put("contacts", map.get("contacts"));
            a.put("vendorMobile", map.get("member_mobile"));
            a.put("vendorEmail", map.get("member_email"));
            a.put("attachment", map.get("attachment"));
            a.put("time", map.get("createdTime"));
            a.put("last", map.get("modifiedTime"));
            a.put("inquiryGoodsEntity", approveListTwo);
            a.put("quoteMultipePurchases", map.get("quoteMultipePurchases"));
            a.put("quoteTotalStrategy", map.get("quoteTotalStrategy"));
            a.put("quoteHermeticStrategy", map.get("quoteHermeticStrategy"));
            a.put("backExpire", map.get("backExpire"));
            a.put("backReson", map.get("backReson"));
            a.put("backAmount", map.get("backAmount"));
            a.put("bolvat", map.get("bolvat"));
            a.put("remarkMessage", map.get("remark_message"));

            approveList.add(a);
        }

        return GatewayResponse.success(approveList.size(), "查询成功", approveList);
    }

    /**
     * 修改询价截止日期
     *
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/expireUpdate")
    @POST
    @Operation(summary = "修改询价截止日期", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> expireUpdate(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        Map<String, Object> body = gatewayParam.getBody();
        if (!body.containsKey("inquiryId")) {
            return GatewayResponse.failed(0, "询价单ID不能为空", null);
        }
        if (!body.containsKey("expire")) {
            return GatewayResponse.failed(0, "新的截止时间不能为空", null);
        }

        //获取当前登录人
        UserDto currentUser = UserUtils.getCurrentUser();
        log.info("----------------------当前登录人：{}------------------------", JSONObject.toJSONString(currentUser));

        //查询当前询价单
        SingleResponse<BOList> listBySimple = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", body.get("inquiryId"));

        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("id", body.get("inquiryId"));
        dataMap.put("expire", body.get("expire"));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date expire = dateFormat.parse((String) body.get("expire"));

        if (expire.compareTo(dateFormat.parse((String) listBySimple.getData().getData().get(0).get("expire"))) < 0) {
            return GatewayResponse.failed
                    ("修改截止日期不可晚于原截止日期" + dateFormat.parse((String) listBySimple.getData().getData().get(0).get("expire")));
        }
        if (expire.compareTo(dateFormat.parse((String) listBySimple.getData().getData().get(0).get("createdTime"))) > 1) {
            return GatewayResponse.failed
                    ("修改截止日期不可早于询价创建时间" + dateFormat.parse((String) listBySimple.getData().getData().get(0).get("createdTime")));
        }
        //更新询价单截止时间
        SingleResponse<BO> boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_INQUIRY, dataMap);

        log.info("------------------------更新修改询价截止日期成功，更新后结果：{}------------------------", JSONObject.toJSONString(boSingleResponse));
        return GatewayResponse.success(0, "更新成功", boSingleResponse.toString());
    }


    /**
     * 还价
     *
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/inquiryBargaining")
    @POST
    @Operation(summary = "还价", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> inquiryBargaining(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        Map<String, Object> body = gatewayParam.getBody();
        if (!body.containsKey("id")) {
            return GatewayResponse.failed(0, "报价商品ID不能为空", null);
        }
        if (!body.containsKey("reason")) {
            return GatewayResponse.failed(0, "还价理由不能为空不能为空", null);
        }
        if (!body.containsKey("counterPrePrice")) {
            return GatewayResponse.failed(0, "还价价格（未税）不能为空", null);
        }

        SingleResponse<BOList> quotationList = BoServiceUtils.findListByIn(ModelConst.T_QUOTATION_GOODS, "id", body.get("id"));
        log.info("------------------------通过报价商品id获取报价商品信息列表：{}------------------------", JSONObject.toJSONString(quotationList));
        if (quotationList.getData().getTotal() == 0) {
            return GatewayResponse.failed("数据库未获取到您要还价的商品信息");
        }
        if (!QuotationStatusEnum.QUOTATION_3_QUOTED.getCode().equals(quotationList.getData().getData().get(0).get("quotation_goods_status"))) {
            return GatewayResponse.failed("只能是已报价中的商品才可以还价");
        }
        if (QuotationStatusEnum.QUOTATION_5_PICKETED.getCode().equals(quotationList.getData().getData().get(0).get("quotation_goods_status"))) {
            return GatewayResponse.failed("已关闭的询价无法还价");
        }

        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("id", body.get("id"));
        dataMap.put("approved_failed_reason", body.get("reason"));
        dataMap.put("counter_pre_price", body.get("counterPrePrice"));
        dataMap.put("counter_price_date", new Date());

        //还价
        SingleResponse<BO> boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, dataMap);

        return GatewayResponse.success(0, "还价成功", boSingleResponse.toString());
    }

    /**
     * 提前截止询价
     *
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/inquiryClose")
    @POST
    @Operation(summary = "提前截止询价", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> inquiryClose(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }

        RequestContext requestContext = RequestContext.get();
        log.info("requestContext:{}", JSONObject.toJSONString(requestContext));

        Map<String, Object> body = gatewayParam.getBody();
        List<String> columnNames = Lists.newArrayList();
        List<Operator> operators = Lists.newArrayList();
        List<Object> columnValues = Lists.newArrayList();

        if (body.containsKey("newInquiryGoodIds") && body.get("newInquiryGoodIds") != null) {
            columnNames.add("id");
            operators.add(Operator.IN);
            String newInquiryGoodIds = MapUtils.getString(body, "newInquiryGoodIds");
            List<String> id = Arrays.asList(newInquiryGoodIds.split(","));
            columnValues.add(id);
        }
        if (body.containsKey("newInquiryGoodsIds") && body.get("newInquiryGoodsIds") != null) {
            columnNames.add("id");
            operators.add(Operator.EQ);
            columnValues.add(body.get("newInquiryGoodsIds"));
        }

        //查询询价商品（分割）
        SingleResponse<BOList> listByIn = BoServiceUtils.findListByIn(ModelConst.T_INQUIRY_GOODS, "id", columnValues.get(0));
        log.info("----------------------询价单（分割）：{}------------------------", JSONObject.toJSONString(listByIn));
        //通过询价商品查询询价单
        SingleResponse<BOList> bySimple = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", listByIn.getData().getData().get(0).get("inquiry_id"));


        //获取当前登录用户
        UserDto member = UserUtils.getCurrentUser();
        Set<ArchitectureCateEnum> organizationArchitecture = RoleUtils.getOrganizationArchitecture(member.getOrganization_id().get(0).getId());
        boolean pmAdmin = organizationArchitecture.contains(ArchitectureCateEnum.PM);
        List<String> iDs = new ArrayList<>();
        if (!pmAdmin) {
            iDs = UserUtils.listSubMemberIds(member.getMemberId());
        }
        if (InquiryStatusEnum.INQUIRY_GOODS_3_QUOTING.getCode().equals(listByIn.getData().getData().get(0).get("inquiry_goods_status")) != true) {
            return GatewayResponse.failed(0, "该商品状态只能是报价中才可提前结束", null);
        }
        if (!pmAdmin && iDs.contains((List<SelectorFormat>) bySimple.getData().getData().get(0).get("member_id"))) {
            return GatewayResponse.failed(0, "没有对该询价的操作权限", null);
        }

        List<Map<String, Object>> ListMap = Lists.newArrayList();
        Object newInquiryGoodIds = body.get("newInquiryGoodIds");
        if (newInquiryGoodIds != null) {
            String newInquiryGoodIdsfg = MapUtils.getString(body, "newInquiryGoodIds");
            List<String> ids = Arrays.asList(newInquiryGoodIdsfg.split(","));
            for (String id : ids) {
                Map<String, Object> dataMap = Maps.newHashMap();
                dataMap.put("id", id);
                dataMap.put("inquiry_goods_status", InquiryStatusEnum.INQUIRY_GOODS_4_END.getCode());
                ListMap.add(dataMap);
            }
        } else {
            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("id", body.get("newInquiryGoodsIds"));
            dataMap.put("inquiry_goods_status", InquiryStatusEnum.INQUIRY_GOODS_4_END.getCode());
            ListMap.add(dataMap);
        }


        //提前截止询价
        SingleResponse<BO> boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_INQUIRY_GOODS, ListMap);
        log.info("----------------------boSingleResponse：{}------------------------", JSONObject.toJSONString(boSingleResponse));

        return GatewayResponse.success(0, "截止询价成功", boSingleResponse.toString());
    }


    /**
     * 创建询价单
     *
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/inquiryCreate")
    @POST
    @Operation(summary = "创建询价单", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> inquiryCreate(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }

        Map<String, Object> body = gatewayParam.getBody();

        //获取当前用户
        UserDto currentUser = UserUtils.getCurrentUser();
        //根据当前用户获得客户端id
        String clientId = "test001";
        if (StringUtils.isBlank(clientId)) {
            return GatewayResponse.failed("ClientID不存在");
        }

        //组织id
        List<SelectorFormat> organization_id = currentUser.getOrganization_id();
        String orgId = organization_id.get(0).getId();


        if (body != null) {
            List<Map<String, Object>> inquiryGoods = (List<Map<String, Object>>) body.get("inquiryGoods");
            for (Map<String, Object> goods : inquiryGoods) {
                if (StringUtils.isNotBlank((CharSequence) inquiryGoods.get(0).get("company"))) {
                    orgId=null;
                    if (currentUser.getOrganization_name().equals("牧原食品股份有限公司")) {
                        orgId = currentUser.getId();
                    }
                    //用于查询包含角色 "ROLE_CUSTOMER_COMPANY_REGION" 的用户，该用户用户维护牧原公司区域对照关系
                    List<UserDto> userDtoList = UserUtils.getOrganizationUserByRoleName("2c9ac0d37c91e0b5017c938142620071", "ROLE_CUSTOMER_COMPANY_REGION");
                    if (userDtoList != null && userDtoList.size() >= 1) {
                        //个人收货地址表查询
                        List<Map<String, Object>> areaList = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_DELIVER_ADDRESS)
                                .selectField("id,member_id,area_id,address,post,alias,default_address,mobile,phone,del,operator,email,skype,qq,receiver_name")
                                .eq("member_id -> '$.id'", userDtoList.get(0).getId())
                                .eq("alias", inquiryGoods.get(0).get("company"))
                                .queryForList();
                        log.info("----------------------areaList：{}------------------------", JSONObject.toJSONString(areaList));
                        if (areaList != null && areaList.size() > 0) {
                            goods.put("post", areaList.get(0).get("post"));
                        }
                    }
                }
            }
        }

        List<Map<String, Object>> inquiryListMap = Lists.newArrayList();
        Map<String, Object> inquiryMap = Maps.newHashMap();
        inquiryMap.put("account_period", body.get("accountPeriod"));
        inquiryMap.put("client_inquiry_id", body.get("clientInquiryId"));
        inquiryMap.put("client_user_id", body.get("clientUserId"));
        inquiryMap.put("cost_center_name", body.get("costCenterName"));
        inquiryMap.put("department_id", body.get("departmentId"));
        inquiryMap.put("department_name", body.get("departmentName"));
        inquiryMap.put("description", body.get("description"));
        inquiryMap.put("expire", body.get("expire"));
        inquiryMap.put("extendsAttr", body.get("extendsAttr"));
        inquiryMap.put("id ", body.get("id"));
        inquiryMap.put("logistics_demand", body.get("logisticsDemand"));
        inquiryMap.put("member_id", null);
        inquiryMap.put("member_name", body.get("memberName"));
        inquiryMap.put("memos", body.get("memos"));
        inquiryMap.put("mobile", body.get("mobile"));
        inquiryMap.put("modifiedBy", body.get("modifiedBy"));
        inquiryMap.put("name", body.get("name"));
        inquiryMap.put("qq", body.get("qq"));
        //对接的询价单 如果开启了 默认密封报价属性 就强制开启密封报价
        boolean isOk = OrgAttributeUtils.isEnabledAttribute(currentUser.getOrganization_id().get(0).getId(), OrganizationAttributeEnum.VERIFY_QUOTEHERMETICSTRATEGY);
        if (isOk) {
            inquiryMap.put("quote_hermetic_strategy", 1);
        }
        inquiryMap.put("quote_min_time_strategy", body.get("quoteMinTimeStrategy"));
        inquiryMap.put("quote_multiple_purchases", body.get("quoteMultipePurchases"));
        boolean deploy = OrgAttributeUtils.isEnabledAttribute(String.valueOf(currentUser.getOrganization_id()), OrganizationAttributeEnum.MULTIPLE_PURCHASES);
        //如果开启了多次购买 客户不传是否多次购买就默认开启
        if (body != null && body.get("quoteMultipePurchases") == null && deploy) {
            inquiryMap.put("quote_multiple_purchases", 1);
        }
        inquiryMap.put("quote_tax_rate_limit", body.get("quoteTaxRateLimit"));
        inquiryMap.put("quote_total_strategy", body.get("quoteTotalStrategy"));
        inquiryMap.put("submit", body.get("submit"));
        inquiryMap.put("createdTime", body.get("time"));
        if (body.get("vendorScope")!=null && "1"==body.get("vendorScope")){
            if (!body.containsKey("organizationVendorIds")) {
                return GatewayResponse.failed("您未填写邀请供应商id，请补充或更换询价方式!");
            }
            //客户查询被邀请的供应商组织
            List<String> listVendorByCustomerId = OrgUtils.listVendorByCustomerId(orgId);
            log.info("----------------------listVendorByCustomerId：{}------------------------", JSONObject.toJSONString(listVendorByCustomerId));

            List<String> inviteOrgIds = listVendorByCustomerId;
            if (inviteOrgIds.isEmpty()) {
                return GatewayResponse.failed("您暂未与供应商有绑定邀请关系，请补充或更换询价方式!");
            }

            List<Map<String, Object>> organizationVendorIds = (List<Map<String, Object>>) body.get("organizationVendorIds");
            Object id = organizationVendorIds.get(0).get("id");
            log.info("----------------------id：{}------------------------", JSONObject.toJSONString(id));
            if (!inviteOrgIds.contains(id)){
                return GatewayResponse.failed("不可选择未邀请的公司!");
            }

        }
        inquiryMap.put("vendor_scope", body.get("vendorScope"));
        inquiryMap.put("vmi_inquiry", body.get("vmiInquiry"));
        inquiryMap.put("operator", null);
        inquiryMap.put("organization_id", null);
        inquiryListMap.add(inquiryMap);
        SingleResponse<BO> boInquiry = BoServiceUtils.createBo(ModelConst.T_INQUIRY, inquiryListMap);
        log.info("----------------------询价单：{}------------------------", JSONObject.toJSONString(boInquiry));

        //供应商组织中间表
        List<Map<String, Object>> inquiryVendorListMap = Lists.newArrayList();
        Map<String, Object> inquiryVendorMap = Maps.newHashMap();
        inquiryVendorMap.put("inquiry_id",inquiryListMap.get(0).get("id"));
        inquiryVendorMap.put("vendor_organization_id", body.get("organizationVendorIds"));
        inquiryVendorListMap.add(inquiryVendorMap);
        SingleResponse<BO> boInquiryVendor = BoServiceUtils.createBo(ModelConst.T_INQUIRY_VENDOR, inquiryVendorListMap);
        log.info("----------------------询价单和供应商中间表：{}------------------------", JSONObject.toJSONString(boInquiryVendor));

        if (body.get("inquiryGoods")==null) {
            return GatewayResponse.failed("询价商品不能为空");
        }

        List<Map<String, Object>> inquiryGoods = (List<Map<String, Object>>) body.get("inquiryGoods");

        String finalOrgId = orgId;
        inquiryGoods.forEach(i ->{
            Map<String, Object> inquiryGoodsMap = Maps.newHashMap();
            if (body != null && ((List<?>) body.get("inquiryGoods")).size() > 0) {
                //牧原询价需要验证企业采购目录的区域跟物料号,存在的话需要关闭掉该询价商品
                if (currentUser.getOrganization_name().equals("牧原食品股份有限公司")==false) {
                    if (!StringUtils.isBlank((String) i.get("sku")) && !StringUtils.isBlank((String) i.get("area"))) {

                        //根据客户组织id,客户sku,询价区域获取牧原同区域同料号询价商品
                        BOList boList = new BOList();
                        // 获取表名
                        Map<String, Object> parameter = Maps.newHashMap();
                        // 拼接sql
                        StringBuilder totalSql = new StringBuilder();// 获取总数
                        StringBuilder querySql = new StringBuilder();// 查询条件
                        StringBuilder listSql = new StringBuilder();// 获取结果

                        totalSql.append("select count(ig.id) from (\n");
                        querySql.append(inquiryGoodsName).append(" as ig\n");
                        querySql.append("left join\n");
                        querySql.append(inquiryName).append(" as i\n");
                        querySql.append("on i.id = ig.inquiry_id\n");
                        querySql.append("where ig.deleted = 0 \n");
                        querySql.append("and ig.inquiry_goods_status = 3\n");
                        querySql.append("and i.organization_id -> '$.id' in (:organizationIds) \n");
                        parameter.put("organizationIds", currentUser.getOrganization_id().get(0).getId());

                        querySql.append("and ig.sku = :sku\n");
                        parameter.put("sku", inquiryGoods.get(0).get("sku"));
                        querySql.append("and ig.area = :area\n");
                        parameter.put("area", inquiryGoods.get(0).get("area"));
                        querySql.append("and ig.id <> :id\n");
                        parameter.put("id", inquiryGoods.get(0).get("id"));

                        listSql.append("select count(ig.id) from \n");
                        listSql.append(querySql);
                        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSql.toString()));

                        List<Map<String, Object>> result = jdbcTemplate.queryForList(listSql.toString(), parameter);
                        log.info("-------------------result：{}-------------------", JSONObject.toJSONString(result));

                        //对结果进行格式化
                        BoResultFormat.resultFormat(result, ModelConst.T_INQUIRY_GOODS, true);
                        boList.setData(result);
                        boList.setSchemaCode(ModelConst.T_INQUIRY_GOODS);
                        log.info("-------------------boList：{}-------------------", JSONObject.toJSONString(boList));


                        //根据客户组织id,客户sku,询价区域获取牧原企业采购目录未下架，未禁用，未到有效期的商品
                        BOList boListTwo = new BOList();
                        // 获取表名
                        Map<String, Object> parameterTwo = Maps.newHashMap();
                        // 拼接sql
                        StringBuilder totalSqlTwo = new StringBuilder();// 获取总数
                        StringBuilder querySqlTwo = new StringBuilder();// 查询条件
                        StringBuilder listSqlTwo = new StringBuilder();// 获取结果

                        totalSqlTwo.append("select gp.* from (\n");
                        querySqlTwo.append(GoodsPurchaseName).append(" as gp\n");
                        querySqlTwo.append("left join\n");
                        querySqlTwo.append("sourcingcenter."+quotationGoodsName).append(" as qg\n");
                        querySqlTwo.append("on qg.id = gp.quotation_goods_id\n");
                        querySqlTwo.append("left join\n");
                        querySqlTwo.append("sourcingcenter."+inquiryGoodsName).append(" as ig\n");
                        querySqlTwo.append("on ig.id = qg.inquiry_goods_id\n");
                        querySqlTwo.append("where gp.deleted = 0\n");
                        querySqlTwo.append("and ig.deleted=0\n");
                        querySqlTwo.append("and gp.saled = 1\n");
                        querySqlTwo.append("and gp.enabled = 1\n");
                        querySqlTwo.append("and gp.expire > now()\n");
                        querySqlTwo.append("and gp.customer_id -> '$.id' in (:customerIds) \n");
                        parameterTwo.put("customerIds", currentUser.getOrganization_id().get(0).getId());
                        querySqlTwo.append("and gp.customer_sku = :customerSku\n");
                        parameterTwo.put("customerSku", inquiryGoods.get(0).get("sku"));
                        querySqlTwo.append("and ig.area = :area\n");
                        parameterTwo.put("area", inquiryGoods.get(0).get("area"));

                        listSqlTwo.append("select gp.* from\n");
                        listSqlTwo.append(querySqlTwo);
                        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSqlTwo.toString()));

                        List<Map<String, Object>> resultTwo = jdbcTemplate.queryForList(listSqlTwo.toString(), parameterTwo);
                        log.info("-------------------resultTwo：{}-------------------", JSONObject.toJSONString(resultTwo));

                        // 对结果进行格式化
                        BoResultFormat.resultFormat(resultTwo, ModelConst.T_GOODS_PURCHASE, true);
                        boListTwo.setData(resultTwo);
                        boListTwo.setSchemaCode(ModelConst.T_GOODS_PURCHASE);
                        log.info("-------------------boListTwo：{}-------------------", JSONObject.toJSONString(boListTwo));


                        //根据组织sku和区域,并且审批任务状态为审批中的报价
                        BOList boListThree = new BOList();
                        // 获取表名
                        Map<String, Object> parameterThree = Maps.newHashMap();
                        // 拼接sql
                        StringBuilder totalSqlThree = new StringBuilder();// 获取总数
                        StringBuilder querySqlThree = new StringBuilder();// 查询条件
                        StringBuilder listSqlThree = new StringBuilder();// 获取结果

                        totalSqlThree.append("select qg.* from (\n");
                        querySqlThree.append(quotationGoodsName).append(" as qg\n");
                        querySqlThree.append("left join\n");
                        querySqlThree.append(inquiryGoodsName).append(" as ig\n");
                        querySqlThree.append("on qg.inquiry_goods_id = ig.id\n");
                        querySqlThree.append("left join\n");
                        querySqlThree.append(inquiryName).append(" as i\n");
                        querySqlThree.append("on ig.inquiry_id = i.id\n");
                        querySqlThree.append("where ig.sku = :sku\n");
                        parameterThree.put("sku", inquiryGoods.get(0).get("sku"));
                        querySqlThree.append("and ig.area = :area\n");
                        parameterThree.put("area", inquiryGoods.get(0).get("area"));
                        querySqlThree.append("and i.organization_id -> '$.id' in (:organizationIds) \n");
                        parameterThree.put("organizationIds", currentUser.getOrganization_id().get(0).getId());
                        querySqlThree.append("and qg.task_ver > 0\n");
                        querySqlThree.append("and ig.deleted = 0\n");
                        querySqlThree.append("and qg.deleted = 0\n");
                        querySqlThree.append("and qg.quotation_goods_status = 3\n");
                        querySqlThree.append("and qg.picketage = 0\n");
                        querySqlThree.append("order by qg.price asc\n");


                        listSqlThree.append("select qg.* from\n");
                        listSqlThree.append(querySqlThree);
                        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSqlThree.toString()));

                        List<Map<String, Object>> resultThree = jdbcTemplate.queryForList(listSqlThree.toString(), parameterThree);
                        log.info("-------------------resultThree：{}-------------------", JSONObject.toJSONString(resultThree));

                        // 对结果进行格式化
                        BoResultFormat.resultFormat(resultThree, ModelConst.T_QUOTATION_GOODS, true);
                        boListThree.setData(resultThree);
                        boListThree.setSchemaCode(ModelConst.T_QUOTATION_GOODS);
                        log.info("-------------------boListThree：{}-------------------", JSONObject.toJSONString(boListThree));

                        Object count = boList.getData().get(0).get("count(ig.id)");
                        Long aLong = Long.valueOf(String.valueOf(count));
                        if (!boListTwo.getData().isEmpty() || aLong>0 || boListThree != null && boListThree.getData().size() >= 1) {
                            //关闭询价
                            i.put("inquiry_goods_status", InquiryStatusEnum.INQUIRY_GOODS_5_CLOSE.getCode());
                            if (!boListTwo.getData().isEmpty()) {
                                i.put("closing_reason", "已存在采购目录的询价商品");
                            }
                            if (boList.getData().size() > 0) {
                                i.put("closing_reason", "已存在报价中的询价商品");
                            }
                            if (boListThree != null && boListThree.getData().size() >= 1) {
                                i.put("closing_reason", "已存在审核中的询价商品");
                            }
                        }
                    }
                }
            }

            //多次购买和开启开启匹配报价
            boolean enabledAttribute = OrgAttributeUtils.isEnabledAttribute(finalOrgId, OrganizationAttributeEnum.AUTO_MATCH_QUOTATION);
            if (body.get("quoteMultipePurchases") != null && body.get("vendorScope")!=null && body.get("vendorScope")== VendorScopeEnum.ALL && enabledAttribute){
                //todo：需要用到消息队列
            }


            //询价商品
            i.get("address");
            inquiryGoodsMap.put("address", i.get("address"));
            inquiryGoodsMap.put("area", i.get("area"));
            //牧原发布寻源根据明细中的客户料号查询附件上传，自动替换寻源明细中的附件;
            //todo：牧原食品股份有限公司--测试暂时写固买
            if (currentUser.getOrganization_name().equals("上海固买供应链管理有限公司")){
                //牧原发布寻源根据询价商品中的客户料号查询，有则替换询价商品中的附件
                Object sku = i.get("sku");
                //通过sku和组织名查询
                BOList boListSo = new BOList();
                Map<String, Object> parameterSo = Maps.newHashMap();
                // 拼接sql
                StringBuilder querySqlSo = new StringBuilder();// 查询条件
                StringBuilder listSqlSo = new StringBuilder();// 获取结果

                querySqlSo.append(inquiryGoodsName).append(" as ig\n");
                querySqlSo.append("where ig.sku = :sku\n");
                parameterSo.put("sku",sku);
                querySqlSo.append("and ig.organization_company_name = '牧原测试组织'\n");
                querySqlSo.append("group by ig.id desc \n");

                listSqlSo.append("select id,organization_company_name,sku,attachment from\n");
                listSqlSo.append(querySqlSo);
                log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSqlSo.toString()));

                List<Map<String, Object>> resultSo = jdbcTemplate.queryForList(listSqlSo.toString(), parameterSo);
                log.info("-------------------resultSo：{}-------------------", JSONObject.toJSONString(resultSo));

                // 对结果进行格式化
                BoResultFormat.resultFormat(resultSo, ModelConst.T_INQUIRY_GOODS, true);
                boListSo.setData(resultSo);
                boListSo.setSchemaCode(ModelConst.T_INQUIRY_GOODS);
                log.info("-------------------boListSo：{}-------------------", JSONObject.toJSONString(boListSo));

                Object attachment = boListSo.getData().get(0).get("attachment");
                inquiryGoodsMap.put("attachment",attachment);
            } else {
                inquiryGoodsMap.put("attachment", i.get("attachment"));
            }
            inquiryGoodsMap.put("bar_code", i.get("barCode"));
            inquiryGoodsMap.put("brand", i.get("brand"));
            inquiryGoodsMap.put("category", i.get("category"));
            inquiryGoodsMap.put("client_id", i.get("clientId"));
            inquiryGoodsMap.put("client_inquiry_goods_id", i.get("clientInquiryGoodsId"));
            inquiryGoodsMap.put("company", i.get("company"));
            inquiryGoodsMap.put("delivery", i.get("delivery"));
            inquiryGoodsMap.put("demand_department", null);
            inquiryGoodsMap.put("description", i.get("description"));
            inquiryGoodsMap.put("historyPurchasePrice", i.get("historyPurchasePrice"));
            inquiryGoodsMap.put("inquiry_id", boInquiry.getData().getBizObjectId());
            inquiryGoodsMap.put("item_type", i.get("itemType"));
            inquiryGoodsMap.put("maximum_stock", i.get("maximumStock"));
            inquiryGoodsMap.put("memo", i.get("memo"));
            inquiryGoodsMap.put("model", i.get("model"));
            inquiryGoodsMap.put("modifiedBy", i.get("modifiedBy"));
            inquiryGoodsMap.put("name", i.get("name"));
            inquiryGoodsMap.put("num", i.get("num"));
            inquiryGoodsMap.put("package_num", i.get("packageNum"));
            inquiryGoodsMap.put("package_unit", i.get("packageUnit"));
            inquiryGoodsMap.put("participation", i.get("participation"));
            inquiryGoodsMap.put("platform_category_name", i.get("platformCategoryName"));
            inquiryGoodsMap.put("quote_count", i.get("quoteCount"));
            inquiryGoodsMap.put("quote_edit_limit", i.get("quoteEditLimit"));
            inquiryGoodsMap.put("quoteEditable", i.get("quoteEditable"));
            inquiryGoodsMap.put("safety_stock_num", i.get("safetyStockNum"));
            inquiryGoodsMap.put("sku", i.get("sku"));
            inquiryGoodsMap.put("spec", i.get("spec"));
            inquiryGoodsMap.put("inquiry_goods_status",InquiryStatusEnum.INQUIRY_GOODS_0_NEW.getCode());
            inquiryGoodsMap.put("createdTime", i.get("time"));
            inquiryGoodsMap.put("unit", i.get("unit"));
            inquiryGoodsMap.put("url", i.get("url"));
            inquiryGoodsMap.put("warehouse", i.get("warehouse"));
            //历史采购价格存扩展字段
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("historyPurchasePrice",i.get("historyPurchasePrice"));
            inquiryGoodsMap.put("extends_attr", JSONObject.toJSONString(jsonObject));
            inquiryGoodsMap.put("operator",null);
            //inquiryGoodsListMap.add(inquiryGoodsMap);
            SingleResponse<BO> boInquiryGoods = BoServiceUtils.createBo(ModelConst.T_INQUIRY_GOODS, Collections.singletonList(inquiryGoodsMap));
            log.info("----------------------询价商品：{}------------------------", JSONObject.toJSONString(boInquiryGoods));
        });

        return GatewayResponse.success(0, "创建询价成功", boInquiry.toString());
    }


    /**
     * 核价定标
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/inquiryDetermine")
    @POST
    @Operation(summary = "核价定标", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> inquiryDetermine(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }

        Map<String,Object> body = gatewayParam.getBody();

        if (!body.containsKey("ids")) {
            return GatewayResponse.failed(0, "报价商品ID不能为空", null);
        }


        //根据报价ids获取已定标的报价单id
        BOList boList = new BOList();
        // 获取表名
        Map<String, Object> parameter = Maps.newHashMap();
        // 拼接sql
        StringBuilder totalSql = new StringBuilder();// 获取总数
        StringBuilder querySql = new StringBuilder();// 查询条件
        StringBuilder listSql = new StringBuilder();// 获取结果

        totalSql.append("select count(*) as count from (\n");
        totalSql.append("select g.id from \n");
        querySql.append(quotationGoodsName).append(" as g\n");
        querySql.append("where g.id in (:ids)\n");
        if (body.containsKey("ids") && body.get("ids") != null) {
            String str = String.valueOf(body.get("ids"));
            String[] ids = str.split(",");
            parameter.put("ids", Arrays.asList(ids));
        }
        listSql.append("select g.id from \n");
        listSql.append(querySql);
        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSql.toString()));

        List<Map<String, Object>> result = jdbcTemplate.queryForList(listSql.toString(),parameter);
        log.info("-------------------result：{}-------------------", JSONObject.toJSONString(result));

        // 对结果进行格式化
        BoResultFormat.resultFormat(result, ModelConst.T_QUOTATION_GOODS, true);
        boList.setData(result);
        boList.setSchemaCode(ModelConst.T_QUOTATION_GOODS);

        if (boList==null) {
            return GatewayResponse.failed(0,"该商品不存在",boList.toString());
        }else {
            SingleResponse<BOList> listBySimple = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS, "id", body.get("ids"));
            if (listBySimple.getData().getData().get(0).get("quotation_goods_status")
                    .equals(QuotationStatusEnum.QUOTATION_5_PICKETED.getCode())==true){
                return GatewayResponse.failed(0,"该商品已定标",boList.toString());
            }
        }

        QuotationGoodsDto quotationGoodsDto = new QuotationGoodsDto();
        String str = String.valueOf(body.get("ids"));
        List<String> ids = Collections.singletonList(str);
        quotationGoodsDto.setQuotationIdList(ids);

        //调用客户定标接口
        SingleResponse<BO> picketage = checkPriceService.picketage(quotationGoodsDto);
        log.info("-------------------picketage：{}-------------------", JSONObject.toJSONString(picketage));
        if (picketage.isSuccess()) {
            return GatewayResponse.success(0,"核价定标成功",picketage.toString());
        } else {
            return GatewayResponse.failed(0,"核价定标失败",picketage.getErrMessage());
        }
    }

    /**
     * 核价定标并修改定标信息
     * @param gatewayParam
     * @return
     * @throws ParseException
     */
    @Path("/inquiryDetermineUpdate")
    @POST
    @Operation(summary = "核价定标并修改定标信息", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> inquiryDetermineUpdate(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }

        Map<String,Object> body = gatewayParam.getBody();

        if (!body.containsKey("items")) {
            return GatewayResponse.failed(0, "items不能为空", null);
        }

        List<Map<String, Object>> items = (List<Map<String, Object>>) body.get("items");

        //通过报价商品id查询
        SingleResponse<BOList> listBySimple = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS, "id", items.get(0).get("quotationGoodsId"));

        if (listBySimple==null) {
            return GatewayResponse.failed(0,"该商品不存在",listBySimple.toString());
        }else {
            if (listBySimple.getData().getData().get(0).get("quotation_goods_status")
                    .equals(QuotationStatusEnum.QUOTATION_5_PICKETED.getCode())==true){
                return GatewayResponse.failed(0,"该商品已定标",listBySimple.toString());
            }
        }


        QuotationGoodsDto quotationGoodsDto = new QuotationGoodsDto();
        String str = String.valueOf(items.get(0).get("quotationGoodsId"));
        List<String> quotationGoodsId = Collections.singletonList(str);
        quotationGoodsDto.setQuotationIdList(quotationGoodsId);

        //调用客户定标接口
        SingleResponse<BO> picketage = checkPriceService.picketage(quotationGoodsDto);
        log.info("-------------------picketage：{}-------------------", JSONObject.toJSONString(picketage));
        if (picketage.isSuccess()) {
            //通过报价商品查询组织采购表
            List<Map<String, Object>> maps = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE)
                    .selectField("id,quotation_goods_id,catalog")
                    .eq("quotation_goods_id",items.get(0).get("quotationGoodsId"))
                    .queryForList();
            log.info("----------------------maps：{}------------------------", JSONObject.toJSONString(maps));

            //修改目录
            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("id", maps.get(0).get("id"));
            dataMap.put("catalog",items.get(0).get("catalog"));

            SingleResponse<BO> boSingleResponse = BoServiceUtils.updateMainBo(ModelConst.T_GOODS_PURCHASE, dataMap);
            log.info("----------------------修改目录：{}------------------------", JSONObject.toJSONString(boSingleResponse));

            return GatewayResponse.success(0,"核价定标成功",picketage.toString());
        } else {
            return GatewayResponse.failed(0,"核价定标失败",picketage.getErrMessage());
        }

    }

    /**
     * 参与报价
     *
     * @param gatewayParam  请求参数
     * @return  响应结果
     */
    @Path("/quotationInvolve")
    @POST
    @Operation(summary = "参与报价", tags = CUSTOM_SERVICE ,description = "inquiryGoodsIds或newInquiryGoodsIds至少传入一个")
//    @AccessLimit(QPS = 1, paramsAsKey = true)
    public GatewayResponse<List<BO>> quotationInvolve(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        Map<String,Object> body = gatewayParam.getBody();
        List<String> inquiryGoodsIds = null;
        if (body.containsKey("newInquiryGoodsIds") && !ObjectUtils.isEmpty(body.get("newInquiryGoodsIds"))) {
            if (body.containsKey("inquiryGoodsIds") && !ObjectUtils.isEmpty(body.get("inquiryGoodsIds")) ) {
                return GatewayResponse.failed("请勿同时传递过期参数类型");
            }
            inquiryGoodsIds = StringUtils.commaDelimitedTrimEmptyListString(body.get("newInquiryGoodsIds").toString());
        } else {
            inquiryGoodsIds = (List<String>) body.get("inquiryGoodsIds");
            log.warn("使用过期参数 [quotation-involve]-inquiryGoodsIds[] , {}", StringUtils.join(inquiryGoodsIds, ","));
        }
        if (null == inquiryGoodsIds || inquiryGoodsIds.isEmpty()) {
            return GatewayResponse.failed("参数不正确");
        }
        UserDto currentUser = UserUtils.getCurrentUser();
        Assert.isTrue(currentUser != null, "获取用户信息失败");
        String memberId = currentUser.getId();
        String clientId = currentUser.getClient_id();
        String orgId = currentUser.getOrganization_id().get(0).getId();
        InquiryGoodsDto inquiryGoodsDto = new InquiryGoodsDto();
        inquiryGoodsDto.setInquiryGoodsIdList(inquiryGoodsIds);
        inquiryGoodsDto.setMemberId(memberId);
        inquiryGoodsDto.setOrgId(orgId);
        inquiryGoodsDto.setIsVirtual(isVirtual(currentUser.getDepartment_id().get(0).getId()));
        SingleResponse<List<BO>> result =quotationService.batchParticipation(inquiryGoodsDto);
        if (result.isSuccess()){
            return GatewayResponse.success(result.getData().size(), "参与报价成功", result.getData());
        }else{
            return GatewayResponse.failed(0, result.getErrMessage(), result.getData());
        }
    }

    /**
     * 重新报价
     *
     * @param gatewayParam  请求参数
     * @return  响应结果
     */
    @Path("/quotationRequote")
    @POST
    @Operation(summary = "重新报价", tags = CUSTOM_SERVICE ,description = "quotationGoodsId,pretaxPrice必填")
    public GatewayResponse<BO> quotationRequote(@Parameter GatewayParam gatewayParam) {
        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        Map<String,Object> body = gatewayParam.getBody();
        if (!body.containsKey("quotationGoodsId") || ObjectUtils.isEmpty(body.get("quotationGoodsId"))) {
            return GatewayResponse.failed(0, "参数为空", null);
        }
        if (!body.containsKey("pretaxPrice") || ObjectUtils.isEmpty(body.get("pretaxPrice"))) {
            return GatewayResponse.failed(0, "参数为空", null);
        }
        List<String> quotationGoodsList = StringUtils.commaDelimitedTrimEmptyListString(body.get("quotationGoodsId").toString());
        QuotationGoodsDto quotationGoodsDto = new QuotationGoodsDto();
        quotationGoodsDto.setQuotationIdList(quotationGoodsList);
        quotationGoodsDto.setPretaxPrice(new BigDecimal(body.get("pretaxPrice").toString()));
        SingleResponse<BO> result =quotationService.counterPrice(quotationGoodsDto);
        if (result.isSuccess()){
            return GatewayResponse.success(0, "重新报价成功", result.getData());
        }else{
            return GatewayResponse.failed(0, result.getErrMessage(), result.getData());
        }
    }

    /**
     * 创建报价
     * @param gatewayParam 请求参数
     * @return {@link GatewayResponse< String>} 响应结果
     * @throws
     * @author zhanjh
     * @date 2021/10/25 19:27
     */
    @Path("/quotationCreate")
    @POST
    @Operation(summary = "创建报价", tags = CUSTOM_SERVICE)
    public GatewayResponse<List<Object>> quotationCreate(@Parameter GatewayParam gatewayParam) {

        if (gatewayParam.getBody() == null || gatewayParam.getBody().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }
        List<Map<String, Object>> quotationGoodList = (List<Map<String, Object>>) gatewayParam.getBody().get("quotationGoods");
        if (quotationGoodList.isEmpty()) {
            return GatewayResponse.failed("参数不能为空");
        }
        log.info("----------------------body：{}------------------------", JSONObject.toJSONString(quotationGoodList));
        //校验报价商品
        List<BO> boList = Lists.newArrayList();
        try{
            for (Map<String,Object> quotationGoods : quotationGoodList) {
                quotationGoods.put("attachment",null == quotationGoods.get("attachment")? null :
                        JsonParseObject.parseObject((String) quotationGoods.get("attachment"), Map.class));

                quotationGoods.put("attachment",null);
                Map<String, Object> quotationGoodsOld = BoServiceUtils.findListBySimple(ModelConst.T_QUOTATION_GOODS, "id", quotationGoods.get("quotationGoodsId")).getData().getData().get(0);
                log.info("------------------------通过报价商品id获取报价商品信息：{}------------------------", JSONObject.toJSONString(quotationGoodsOld));

                Map<String, Object> inquiryGoodsMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", quotationGoodsOld.get("inquiry_goods_id")).getData().getData().get(0);
                log.info("------------------------通过询价商品id获取询价商品信息：{}------------------------", JSONObject.toJSONString(inquiryGoodsMap));

                Map<String, Object> inquiryMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", inquiryGoodsMap.get("inquiry_id")).getData().getData().get(0);
                log.info("------------------------通过询价单id获取询价单信息：{}------------------------", JSONObject.toJSONString(inquiryMap));

                int quoteMultiplePurchases = Integer.parseInt(inquiryMap.get("quote_multiple_purchases").toString());
                if (null == quotationGoods.get("clientQuotationGoodsId")) {
                    return GatewayResponse.failed("对接客户报价商品id为空");
                }
                if (null == quotationGoods.get("taxRate")) {
                    return GatewayResponse.failed("税率为空");
                }
                if (null == quotationGoods.get("expire")) {
                    return GatewayResponse.failed("报价截止日期为空");
                }
                Date quotationExpire = DateUtils.parseDate(quotationGoods.get("expire").toString());
                if (quotationExpire.getTime() <= System.currentTimeMillis()) {
                    return GatewayResponse.failed("报价截止日期小于或等于当前时间异常");
                }

                if (ObjectUtils.isEmpty(quotationGoods.get("address"))) {
                    return GatewayResponse.failed("发货地址为空");
                }
                // 报价有效期不能大于366天
                Date inquiryExpire = DateUtils.parseDate(inquiryMap.get("expire").toString());
                if (org.springframework.util.StringUtils.isEmpty(quotationGoods.get("expire"))) {
                    return GatewayResponse.failed("报价有效期不能为空");
                }

                if (quotationExpire.getTime() - DateUtils.addDays(inquiryExpire, 366).getTime() > 0) {
                    return GatewayResponse.failed("报价单【" + quotationGoodsOld.get("id") + "】报价有效期大于询价截止日期366天");
                }
                if (quotationExpire.getTime() < DateUtils.parseDate(inquiryMap.get("quote_min_time_strategy").toString()).getTime()) {
                    return GatewayResponse.failed("过期时间不能小于询价报价有效期" + inquiryMap.get("quote_min_time_strategy"));
                }
                if ("1".equals(inquiryGoodsMap.get("item_type").toString())) {
                    if (quotationGoods.get("attachment") == null || ObjectUtils.isEmpty(quotationGoods.get("attachment"))) {
                        return GatewayResponse.failed("必须上传代理资质！");
                    }
                }
                BigDecimal pretaxPrice = BigDecimal.ZERO;
                BigDecimal taxRate = new BigDecimal(String.valueOf(quotationGoods.get("taxRate")));
                BigDecimal price = BigDecimal.ZERO;
                if(quotationGoods.get("price") != null &&quotationGoods.get("pretaxPrice") != null){
                    pretaxPrice = new BigDecimal(String.valueOf(quotationGoods.get("pretaxPrice")));
                    price = new BigDecimal(String.valueOf(quotationGoods.get("price")));
                } else if (quotationGoods.get("price") == null &&quotationGoods.get("pretaxPrice") != null) {
                    pretaxPrice = new BigDecimal(String.valueOf(quotationGoods.get("pretaxPrice")));
                    quotationGoods.put("price", FinancialCalculationUtils.calculatePriceByPretaxPrice(pretaxPrice, taxRate));
                } else if (quotationGoods.get("price") != null && quotationGoods.get("pretaxPrice") == null) {
                    //判断含税价为空未税价不为空，根据含税价计算未税价
                    price = new BigDecimal(String.valueOf(quotationGoods.get("price")));
                    quotationGoods.put("pretaxPrice",TaxRateUtils.calculateTaxBefore(price, taxRate));
                } else {
                    return GatewayResponse.failed("请输入报价单" + quotationGoods.get("quotationGoodsId") + "的未税或者含税单价！");
                }
                BigDecimal freight = BigDecimal.ZERO;
                BigDecimal pretaxFreight = BigDecimal.ZERO;
                if(quotationGoods.get("freight") != null && quotationGoods.get("pretaxFreight") != null){
                    pretaxFreight = new BigDecimal(String.valueOf(quotationGoods.get("pretaxFreight")));
                    freight = new BigDecimal(String.valueOf(quotationGoods.get("freight")));
                } else if (quotationGoods.get("freight") == null && quotationGoods.get("pretaxFreight") != null) {
                    pretaxFreight = new BigDecimal(String.valueOf(quotationGoods.get("pretaxFreight")));
                    quotationGoods.put("freight",TaxRateUtils.calculateTaxAfter(pretaxFreight, taxRate));
                } else if (quotationGoods.get("freight") != null && quotationGoods.get("pretaxFreight") == null) {
                    //判断含税价为空未税价不为空，根据含税价计算未税价
                    freight = new BigDecimal(String.valueOf(quotationGoods.get("freight")));
                    quotationGoods.put("pretaxFreight",TaxRateUtils.calculateTaxBefore(freight, taxRate));
                } else {
                    quotationGoods.put("freight",0.0);
                    quotationGoods.put("pretaxFreight",0.0);
                }
                // todo 施耐德询价校验货期不能大于询价时候的货期
                if (QuotationStatusEnum.QUOTATION_0_NEW.getCode().equals(quotationGoodsOld.get("quotation_goods_status").toString())
                        || QuotationStatusEnum.QUOTATION_2_APPROVE_NO.getCode().equals(quotationGoodsOld.get("quotation_goods_status").toString())
                        || QuotationStatusEnum.QUOTATION_4_APPROVE_BACK.getCode().equals(quotationGoodsOld.get("quotation_goods_status").toString())) {
                    BigDecimal number = BigDecimal.ZERO;
                    if ("1".equals(inquiryGoodsMap.get("quote_edit_limit").toString())) {
                        quotationGoodsOld.put("name", quotationGoods.get("name"));
                        quotationGoodsOld.put("brand", quotationGoods.get("brand"));
                        quotationGoodsOld.put("model", quotationGoods.get("model"));
                        quotationGoodsOld.put("spec", quotationGoods.get("spec"));
                        quotationGoodsOld.put("num", quotationGoods.get("num"));
                        quotationGoodsOld.put("unit", quotationGoods.get("unit"));
                        quotationGoodsOld.put("package_num", quotationGoods.get("packageNum"));
                        quotationGoodsOld.put("package_unit", quotationGoods.get("packageUnit"));
                        number = new BigDecimal(String.valueOf(quotationGoods.get("num")));
                    }else {
                        number = new BigDecimal(String.valueOf(inquiryGoodsMap.get("num")));
                        //不接受替换商品
                    }
                    BigDecimal taxRateFreight = null == quotationGoods.get("taxRateFreight")? BigDecimal.valueOf(0.06) :new BigDecimal(String.valueOf(quotationGoods.get("taxRateFreight")));
                    BigDecimal taxPayableFreight = FinancialCalculationUtils.calculatePayableFreightByPretaxFreight(pretaxFreight, taxRateFreight);
                    BigDecimal pretaxAmount = FinancialCalculationUtils.calculatePretaxAmountByPretaxPriceAndPretaxFreight(pretaxPrice, pretaxFreight, number);
                    BigDecimal amount = FinancialCalculationUtils.calculateAmountByPretaxPriceAndPretaxFreight(pretaxPrice, pretaxFreight, taxRate, taxRateFreight, number);
                    BigDecimal taxPayable = FinancialCalculationUtils.calculateTaxPayableByPretaxPrice(pretaxPrice, taxRate, number);
                    BigDecimal total = FinancialCalculationUtils.calculateTotalByPretaxPrice(pretaxPrice, taxRate, number);

                    quotationGoodsOld.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_0_NEW.getCode());
                    quotationGoodsOld.put("org_category_name", quotationGoods.get("category"));
                    quotationGoodsOld.put("sku", quotationGoods.get("sku"));
                    quotationGoodsOld.put("delivery", quotationGoods.get("delivery") == null ? 0 : quotationGoods.get("delivery"));
                    quotationGoodsOld.put("expire", quotationGoods.get("expire"));
                    quotationGoodsOld.put("address", quotationGoods.get("address"));
                    quotationGoodsOld.put("description", quotationGoods.get("description"));
                    // region 报价金额
                    quotationGoodsOld.put("tax_rate", quotationGoods.get("taxRate"));
                    quotationGoodsOld.put("pretax_freight", quotationGoods.get("pretaxFreight"));
                    quotationGoodsOld.put("pretax_price", quotationGoods.get("pretaxPrice"));
                    quotationGoodsOld.put("price", quotationGoods.get("price"));
                    quotationGoodsOld.put("pretax_total", quotationGoods.get("pretaxTotal"));

                    quotationGoodsOld.put("total", total);
                    quotationGoodsOld.put("amount", amount);
                    quotationGoodsOld.put("tax_payable", taxPayable);
                    quotationGoodsOld.put("tax_rate_freight", taxRateFreight);
                    quotationGoodsOld.put("pretax_amount", pretaxAmount);
                    quotationGoodsOld.put("tax_payable_freight", taxPayableFreight);
                    quotationGoodsOld.put("freight", quotationGoods.get("freight"));
                    quotationGoodsOld.put("attachment", quotationGoods.get("attachment"));
                    //TODO 模型必填，swagger没有传递
                    quotationGoodsOld.put("maximum",Optional.ofNullable(quotationGoodsOld.get("maximum")).orElse(inquiryGoodsMap.get("num")));
                    quotationGoodsOld.put("min_order", Optional.ofNullable(quotationGoodsOld.get("min_order")).orElse(inquiryGoodsMap.get("num")));

                    quotationGoodsOld.put("client_id", quotationGoods.get("clientId"));
                    quotationGoodsOld.put("client_quotation_goods_id", quotationGoods.get("clientQuotationGoodsId"));
                    quotationGoodsOld.put("organization_company_name", quotationGoods.get("organizationName"));
                    log.info("--------------quotationGoodsOld-----------：{}", JSONObject.toJSONString(quotationGoodsOld));
                    //平台报价运费通过手动输入
                    if ("1".equals(quotationGoodsOld.get("auto_quotation").toString())) {
                        quotationGoodsOld.put("freight", quotationGoods.get("freight"));
                    }
                    // todo 通过listBO接口查询出来的结果不能直接进行update，需要做下处理
                    quotationGoodsOld = quotationService.formatQuotationGoods(quotationGoodsOld);
                    SingleResponse<BO> quotationUpdateBO = BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, quotationGoodsOld);
                    log.info("------------------------更新报价商品成功，更新后数据：{}------------------------", JSONObject.toJSONString(quotationUpdateBO));
                    boList.add(quotationUpdateBO.getData());
                }
            }
        }catch (InquiryException e) {
            return GatewayResponse.failed("创建报价失败，请联系管理员！");
        }
        submitQuotation(boList);
        return GatewayResponse.success(boList.size(), "报价成功", boList.stream().map(bo ->bo.getData().get("id")).collect(Collectors.toList()));
    }

    public void submitQuotation(List<BO> boList) {
        if (boList == null || boList.isEmpty()) {
            GatewayResponse.failed(0, "报价提交参数为空", null);
        }
        List<Map<String,Object>> list=BoServiceUtils.findListByIn(ModelConst.T_QUOTATION_GOODS, "id", boList.stream().
                map(bo -> bo.getData().get("id")).collect(Collectors.toList())).getData().getData();
        Map<String, List<Map<String,Object>>> groupByVendor = list.stream().collect(Collectors.groupingBy(
                bo ->((List<SelectorFormat>)bo.get("vendor_organization_id")).get(0).getId()));
        Set<String> integers = groupByVendor.keySet();
        List<BO> result = new ArrayList<>();
        List<Map<String, Object>> approvedHistoryList = new ArrayList<>();
        for (String vendorId : integers) {
            List<Map<String,Object>> quotationsByVendor = groupByVendor.get(vendorId);

            //检查组织是否需要审批 审批属性开启
            boolean noMixedOrder = OrgAttributeUtils.isEnabledAttribute(vendorId, OrganizationAttributeEnum.QUOTATION_APPROVAL);
            if (noMixedOrder) {
                //验证表单
                QuotationStatusEnum quotationNew = QuotationStatusEnum.QUOTATION_0_NEW;
                Set<String> inquiryIDs = new HashSet<>();
                List<String> inquiryGoodsIDs = new ArrayList<>();
                for (Map<String,Object> qge : list) {
                    Map<String, Object> inquiryGoodsMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", qge.get("inquiry_goods_id")).getData().getData().get(0);
                    Map<String, Object> inquiryMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", inquiryGoodsMap.get("inquiry_id")).getData().getData().get(0);
                    if (null == qge) {
                        throw new BizException("报价单不存在");
                    }
                    if (qge.get("quotation_goods_status") != quotationNew) {
                        throw new BizException("报价单不是新建");
                    }
                    if (inquiryGoodsMap == null || inquiryMap == null || inquiryMap.get("id") == null) {
                        throw new BizException("qge.getInquiryGoods() == null || qge.getInquiryGoods().getInquiry() == null || qge.getInquiryGoods().getInquiry().getId() == null");
                    }

                    String status = inquiryGoodsMap.get("inquiry_goods_status").toString();
                    if (!(status == InquiryStatusEnum.INQUIRY_GOODS_3_QUOTING.getCode() || status == InquiryStatusEnum.INQUIRY_GOODS_4_END.getCode())) {
                        throw new BizException("报价商品为" + qge.get("id") + "的询价商品" + InquiryStatusEnum.get(status).getDes() + ", 无法继续操作");
                    }

                    // 公采给施耐德开发的平台客户端ID
                    if (ApiClientConstants.SCHNEIDER.equals(qge.get("client_id"))) {
                        if (null != qge.get("description") && !"".equals(qge.get("description"))) {
                            throw new BizException("施耐德组织的询价商品不能在报价时被备注");
                        }
                    }

                    inquiryIDs.add(inquiryMap.get("id").toString());
                    inquiryGoodsIDs.add(inquiryGoodsMap.get("id").toString());
                    //验证单一询价商品重复报价
                    if (new HashSet<>(inquiryGoodsIDs).size() != inquiryGoodsIDs.size()) {
                        throw new BizException("对同一个询价商品进行了重复报价");
                    }
                }
                for (Map<String,Object> quotationGoods : quotationsByVendor) {
                    Map<String, Object> parameter = Maps.newHashMap();
                    parameter.put("id",quotationGoods.get("id"));
                    parameter.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_1_APPROVE.getCode());
                    quotationGoods.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_1_APPROVE.getCode());
                    result.add(BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, parameter).getData());
                }
                //未开启审批
            } else {
                for (Map<String,Object> quotationGoods : quotationsByVendor) {
                    Map<String, Object> inquiryGoodsMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY_GOODS, "id", quotationGoods.get("inquiry_goods_id")).getData().getData().get(0);
                    Map<String, Object> inquiryMap = BoServiceUtils.findListBySimple(ModelConst.T_INQUIRY, "id", inquiryGoodsMap.get("inquiry_id")).getData().getData().get(0);
                    if (QuotationStatusEnum.QUOTATION_2_APPROVE_NO.getCode().equals(quotationGoods.get("quotation_goods_status"))
                            || QuotationStatusEnum.QUOTATION_0_NEW.getCode().equals(quotationGoods.get("quotation_goods_status"))) {
                        quotationGoods.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_3_QUOTED.getCode());
                        quotationGoods.put("modifiedTime", new Date());
                        // 公采给施耐德开发的平台客户端ID
                        if (ApiClientConstants.SCHNEIDER.equals(quotationGoods.get("client_id"))) {
                            if (null != quotationGoods.get("description") && !"".equals(quotationGoods.get("description"))) {
                                throw new BizException("施耐德组织的询价商品不能在报价时被备注");
                            }
                        }
                        //查询是否存在邀请关系,如果是邀请供应商（即原有供应商）,则把原有供应商id，存入json
                        Map<String, Object> parameter = Maps.newHashMap();
                        parameter.put("id",quotationGoods.get("id"));
                        parameter.put("quotation_goods_status", QuotationStatusEnum.QUOTATION_3_QUOTED.getCode());
                        SingleResponse<BO> quotationResult = BoServiceUtils.updateMainBo(ModelConst.T_QUOTATION_GOODS, parameter);
                        result.add(quotationResult.getData());
                        // 修改报价次数
                        if (!updateQuotationCount(Arrays.asList(inquiryGoodsMap.get("id").toString()))) {
                            throw new BizException("询价商品报价次数修改失败，请重新操作");
                        }
                        //询竞价单往报价竞价历史表存入数据
                        Map<String, Object> approvedHistoryData;
                        if ("1".equals(inquiryMap.get("quote_public_bidding"))) {
                            if (quotationResult.isSuccess()) {
                                QuotationGoodsApprovedHistoryDto approvedHistoryDto = new QuotationGoodsApprovedHistoryDto();
                                approvedHistoryList.add(setApprovedHistory(approvedHistoryDto, quotationGoods));
                            }
                        }
                    }
                }
            }
        }
        SingleResponse<BO> approvedHistoryResult = BoServiceUtils.createBo(ModelConst.T_QUOTATION_GOODS_APP_HIS, approvedHistoryList);
    }

    /**
     * 修改询价商品的报价次数
     *
     * @param inquiryGoodsIdList 询价商品id
     */
    private boolean updateQuotationCount(List<String> inquiryGoodsIdList) {
        boolean result = true;
        StringBuilder builder;
        Map<String, Object> parameter = Maps.newHashMap();
        parameter.put("deleted", 0);
        parameter.put("status", Collections.singletonList(QuotationStatusEnum.QUOTATION_3_QUOTED.getCode()));
        for (String inquiryGoodsId : inquiryGoodsIdList) {
            builder = new StringBuilder();
            builder.append("update\n")
                    .append(getTableName(ModelConst.T_INQUIRY_GOODS)).append("\n")
                    .append("set quote_count = \n")
                    .append("(select count(*) from\n")
                    .append(getTableName(ModelConst.T_QUOTATION_GOODS)).append("\n")
                    .append("where 1 = 1\n")
                    .append("and deleted = :deleted\n")
                    .append("and inquiry_goods_id = :inquiryGoodsId\n")
                    .append("and quotation_goods_status in (:status))\n")
                    .append("where id = :inquiryGoodsId\n");
            parameter.put("inquiryGoodsId", inquiryGoodsId);
            log.info("sql = {}, parameters = {}", builder, JSONObject.toJSONString(parameter));
            if (jdbcTemplate.update(builder.toString(), parameter) != 1) {
                result = false;
                break;
            }
        }
        return result;
    }

    /**
     * 核退报价商品表数据赋值
     *
     * @param approvedHistoryDto    还价请求参数
     * @param quotation             报价商品数据
     * @return                      还价商品
     */
    private Map<String, Object> setApprovedHistory(QuotationGoodsApprovedHistoryDto approvedHistoryDto, Map<String, Object> quotation) {
        Map<String, Object> approvedHistoryMap = Maps.newHashMap();
        approvedHistoryMap.put("approved_failed_reason", approvedHistoryDto.getReason());
        approvedHistoryMap.put("counter_price_date", approvedHistoryDto.getCounterPriceDate());
        approvedHistoryMap.put("counter_pre_price", approvedHistoryDto.getCounterPrePrice());
        approvedHistoryMap.put("org_category_name", quotation.get("org_category_name"));
        approvedHistoryMap.put("quotation_id", quotation.get("id"));
        approvedHistoryMap.put("name", quotation.get("name"));
        approvedHistoryMap.put("brand", quotation.get("brand"));
        approvedHistoryMap.put("model", quotation.get("model"));
        approvedHistoryMap.put("spec", quotation.get("spec"));
        approvedHistoryMap.put("price", quotation.get("price"));
        //todo 产品目前bug，需要手动解决，7.3版本修复
        approvedHistoryMap.put("delivery", quotation.get("delivery"));
        approvedHistoryMap.put("num", quotation.get("num"));
        approvedHistoryMap.put("total", quotation.get("total"));
        approvedHistoryMap.put("unit", quotation.get("unit"));
        approvedHistoryMap.put("package_num", quotation.get("package_num"));
        approvedHistoryMap.put("package_unit", quotation.get("package_unit"));
        approvedHistoryMap.put("freight", quotation.get("freight"));
        approvedHistoryMap.put("taxRate", quotation.get("taxRate"));
        approvedHistoryMap.put("amount", quotation.get("amount"));
        approvedHistoryMap.put("expire", quotation.get("expire"));
        approvedHistoryMap.put("address", quotation.get("address"));
        approvedHistoryMap.put("attachment", quotation.get("attachment"));
        approvedHistoryMap.put("picketage", "1".equals(String.valueOf(quotation.get("picketage"))));
        approvedHistoryMap.put("description", quotation.get("description"));
        approvedHistoryMap.put("pretax_price", quotation.get("pretax_price"));
        approvedHistoryMap.put("pretax_total", quotation.get("pretax_total"));
        approvedHistoryMap.put("tax_payable", quotation.get("tax_payable"));
        approvedHistoryMap.put("pretax_freight", quotation.get("pretax_freight"));
        approvedHistoryMap.put("tax_payable_freight", quotation.get("tax_payable_freight"));
        approvedHistoryMap.put("tax_rate_freight", quotation.get("tax_rate_freight"));
        approvedHistoryMap.put("pretax_amount", quotation.get("pretax_amount"));
        return approvedHistoryMap;
    }

    /**
     * 判断当前供应商是否为虚拟供应商
     *
     * @return
     */
    public boolean isVirtual(String deptId) {
        if (null == deptId) {
            return false;
        }
        Map<String, Object> organization = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_ORGANIZATION)
                .selectField("*").eq("id", deptId).queryForMap();
        if (!CollectionUtils.isEmpty(organization) && organization.get("virtual").toString().equals("1")) {
            return true;
        }
        return false;
    }


    @Path("/skuAndAliasByCalibrated")
    @POST
    @Operation(summary = "根据客户商品料号和公司查询定标商品", tags = CUSTOM_SERVICE)
    public GatewayResponse<String> skuAndAliasByCalibrated(@Parameter GatewayParam gatewayParam) throws ParseException {
        if (gatewayParam.getQuery() == null || gatewayParam.getQuery().size() == 0) {
            return GatewayResponse.failed(0, "参数不能为空，请检查参数", null);
        }

        Map<String, Object> query = gatewayParam.getQuery();
        if (!query.containsKey("alias")) {
            return GatewayResponse.failed(0, "公司不能为空", null);
        }
        if (!query.containsKey("sku")) {
            return GatewayResponse.failed(0, "料号不能为空", null);
        }

        //当前登录用户获取会员id
        UserDto currentUser = UserUtils.getCurrentUser();
        String userId = currentUser.getId();


        //通过公司区域对照表查对应区域
        List<Map<String, Object>> maps = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_DELIVER_ADDRESS)
                .selectField("id,JSON_UNQUOTE(area_id -> '$.address'),alias")
                .eq("member_id -> '$.id'","2c9ac00d78a69a5a0178abed5717000a")//暂时写死会员id
                .eq("alias",query.get("alias"))
                .queryForList();
        log.info("----------------------maps：{}------------------------", JSONObject.toJSONString(maps));


        //todo：通过区域+料号查询已定标商品
        BOList boList = new BOList();

        Map<String, Object> parameterCalibrated = Maps.newHashMap();
        // 拼接sql
        StringBuilder querySqlCalibrated = new StringBuilder();// 查询条件
        StringBuilder listSqlCalibrated = new StringBuilder();// 获取结果

        querySqlCalibrated.append(inquiryGoodsName).append(" as ig\n");
        querySqlCalibrated.append("where ig.deleted = 0 \n");
        querySqlCalibrated.append("and ig.picketaged = 0 \n");
        querySqlCalibrated.append("and ig.area = :area  \n");
        parameterCalibrated.put("area", maps.get(0).get("JSON_UNQUOTE(area_id -> '$.address')"));
        querySqlCalibrated.append("and ig.sku = :sku \n");
        parameterCalibrated.put("sku", query.get("sku"));
        listSqlCalibrated.append("select ig.* from \n");
        listSqlCalibrated.append(querySqlCalibrated);
        log.info("-------------------sql语句：{}-------------------", JSONObject.toJSONString(listSqlCalibrated.toString()));

        List<Map<String, Object>> resultCalibrated = jdbcTemplate.queryForList(listSqlCalibrated.toString(), parameterCalibrated);
        log.info("-------------------根据客户商品料号和公司查询定标商品：{}-------------------", JSONObject.toJSONString(resultCalibrated));


        // 对结果进行格式化
        BoResultFormat.resultFormat(resultCalibrated, ModelConst.T_INQUIRY_GOODS, true);
        boList.setData(resultCalibrated);
        boList.setSchemaCode(ModelConst.T_INQUIRY_GOODS);
        log.info("-------------------boList：{}-------------------", JSONObject.toJSONString(boList));

        return GatewayResponse.success(0, "查询成功", boList.getData().toString());
    }



}

